package com.hyj.serve.manage.entity.firewall;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.huitian.mybatis.plus.util.MPUtils;
import com.hyj.serve.manage.configure.exception.ServiceException;
import com.hyj.serve.manage.enums.ProtocolEnum;
import lombok.Data;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * @author HeYuJie
 * @date 2022/6/6
 */
@Data
public class PortRule extends RuleItem {

    public static final String TAG_NAME = "port";

    private String type = TAG_NAME;

    // 端口协议必须同时存在
    // 协议
    private ProtocolEnum protocol = ProtocolEnum.tcp;
    // 端口
    private String port;


    public ProtocolEnum getProtocol() {
        return ObjectUtil.defaultIfNull(protocol, ProtocolEnum.tcp);
    }

    public void setPort(String port) {
        if(StrUtil.isEmpty(port)){
            this.port = null;
            return;
        }
        if(!port.matches("^(\\d+)(-\\d+)?$")){
            throw new ServiceException("端口设置错误，请指定正确的端口：3306或范围3306-3309");
        }
        this.port = port;
    }


    @Override
    public String serializeXml(String prefix) {
        if(StrUtil.isEmpty(port)){
            return null;
        }
        return MPUtils.str(prefix, "<", TAG_NAME, " protocol=\"", protocol.name(), "\" port=\"", port, "\"/>");
    }

    public static PortRule deserializeXml(String xml){
        if(StrUtil.isEmpty(xml)){
            return null;
        }
        try {
            Document document = DocumentHelper.parseText(xml);
            Element rootElement = document.getRootElement();
            return deserializeXml(rootElement);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static PortRule deserializeXml(Element xml){
        if(xml == null || !xml.getName().equalsIgnoreCase(TAG_NAME)){
            return null;
        }

        PortRule rule = new PortRule();
        rule.port = xml.attributeValue("port");
        rule.protocol = ProtocolEnum.valueOf(xml.attributeValue("protocol"));
        return rule;
    }

}
